//
//  TeachManagementChildController.m
//  Coach_HaiGeEr
//
//  Created by liuchen on 2018/9/28.
//  Copyright © 2018年 海格尔. All rights reserved.
//

#import "TeachManagementChildController.h"
#import "TeachManagementCell.h"
#import "TFDropDownMenuView.h"
#import "TeachManagementSearchView.h"
#import "TeachManagementModel.h"
#import "MJExtension.h"
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import <CoreTelephony/CTCarrier.h>
#import <MJRefresh.h>

@interface TeachManagementChildController ()<TeachManagementSearchViewDelegate,TFDropDownMenuViewDelegate,TeachManagementCellDelegate,TeachManagementButtonsInCellScrollViewDelegate,UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong) UIImageView *noDataImgView;
@property (nonatomic,strong) UITableView *ownTableView;
@property (nonatomic,strong) TFDropDownMenuView *selectView;
@property (nonatomic,weak) TeachManagementSearchView *searchView;
@property (nonatomic,strong) NSArray *dataArray;
@property (nonatomic,assign) NSInteger size;
@property (nonatomic,assign) NSInteger currStatus;
@property (nonatomic,copy) NSString *trainItem;
@property (nonatomic,copy) NSString *countOrder;
@property (nonatomic,copy) NSString *studentName;
@property (nonatomic,assign) BOOL loadState;
@end

@implementation TeachManagementChildController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[CoachTabBarController shareLZHTabbarController].tabBar setHidden:YES];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createSubViews];
    [self loadDataWithPage:self.size WithCurrStatus:self.currStatus WithCountOrder:self.countOrder WithTrainItem:self.trainItem WithStudentName:self.studentName];
}

#pragma mark ==========加载数据==========
- (void)loadDataWithPage:(NSInteger)size WithCurrStatus:(NSInteger)currStatus WithCountOrder:(NSString *)countOrder WithTrainItem:(NSString *)trainItem WithStudentName:(NSString *)studentName{
    self.loadState = NO;
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setValue:[NSNumber numberWithInteger:size] forKey:@"size"];
    [dic setValue:[NSNumber numberWithInteger:1] forKey:@"page"];
    [dic setValue:[NSNumber numberWithInteger:self.num] forKey:@"subject"];
    [dic setValue:[NSNumber numberWithInteger:currStatus] forKey:@"currStatus"];
    [dic setValue:countOrder forKey:@"countOrder"];
    [dic setValue:studentName==nil?@"":studentName forKey:@"studentName"];
    [dic setValue:trainItem forKey:@"trainItem"];
    [[NetworkEngine sharedClient] GETByToken:TEACHMANAGEMENTList data:dic success:^(id responseObject) {
        [self hideHUD];
        if ([[responseObject objectForKey:@"code"] integerValue] == 1) {
            if ([[responseObject objectForKey:@"data"] count]==0) {
                self.ownTableView.hidden = YES;
                self.noDataImgView.hidden = NO;
            }else {
                if (self.ownTableView.hidden == YES) {
                    self.noDataImgView.hidden = YES;
                    self.ownTableView.hidden = NO;
                }
                self.ownTableView.mj_footer.state = MJRefreshStateIdle;
                if (size==10) {
                    self.dataArray = nil;
                    self.dataArray = [TeachManagementModel mj_objectArrayWithKeyValuesArray:[responseObject objectForKey:@"data"]];
                }else{
                    if ([[responseObject objectForKey:@"data"] count]==self.dataArray.count && [[responseObject objectForKey:@"data"] count]<=size) {
                        self.ownTableView.mj_footer.state = MJRefreshStateNoMoreData;
                    } else {
                        self.dataArray = [TeachManagementModel mj_objectArrayWithKeyValuesArray:[responseObject objectForKey:@"data"]];
                    }
                }
            }
            [self.ownTableView reloadData];
        }else if ([[responseObject objectForKey:@"code"] integerValue] == 2) {
            [self toLoginVC];
        } else {[self showMessage:[responseObject objectForKey:@"msg"]];}
    } failure:^(NSString *error) {
        [self showError:error];
    }];
}
- (void)loadNewData{
    [self showLoading];
    self.size = 10;
    [self loadDataWithPage:self.size WithCurrStatus:self.currStatus WithCountOrder:self.countOrder WithTrainItem:self.trainItem WithStudentName:self.studentName];
    [self.ownTableView.mj_header endRefreshing];
}
- (void)loadMoreData{
    [self showLoading];
    self.size = self.size+10;
    [self loadDataWithPage:self.size WithCurrStatus:self.currStatus WithCountOrder:self.countOrder WithTrainItem:self.trainItem WithStudentName:self.studentName];
    [self.ownTableView.mj_footer endRefreshing];
}

#pragma mark ==========视图==========
- (void)createSubViews{
    self.size = 10;
    self.countOrder = @"asc";
    self.view.backgroundColor = [UIColor whiteColor];
    TeachManagementSearchView *searchView = [[TeachManagementSearchView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 95*SCALEUNIT) WithZjkmNum:self.num];
    searchView.delegate = self;
    _searchView = searchView;
    [self.view addSubview:self.searchView];
    [self.view addSubview:self.selectView];
    [self.view addSubview:self.noDataImgView];
    [self.view addSubview:self.ownTableView];
}

#pragma mark ==========懒加载==========
- (TFDropDownMenuView *)selectView{
    if (!_selectView) {
        NSMutableArray *array1 = [[NSMutableArray alloc] init];
        NSMutableArray *array2 = [NSMutableArray arrayWithArray:self.subjectTwoArr];
        NSMutableArray *array3 = [NSMutableArray arrayWithObjects:@"全部学员", @"在培学员", nil];
        NSMutableArray *data1 = self.num==2?[NSMutableArray arrayWithObjects:array1,array2,array3, nil]:[NSMutableArray arrayWithObjects:array1,array3, nil];
        _selectView = [[TFDropDownMenuView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.searchView.frame), self.view.frame.size.width, 90*SCALEUNIT) firstArray:data1 secondArray:nil titleArray:self.num==2?@[@"练习次数",@"全部项目",@"全部学员"]:@[@"练习次数",@"全部学员"]];
        _selectView.delegate = self;
    }
    return _selectView;
}
- (UIImageView *)noDataImgView{
    if (!_noDataImgView) {
        _noDataImgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 179*2*SCALEUNIT, 140*2*SCALEUNIT)];
        _noDataImgView.image = [UIImage imageNamed:@"CoachNoDataImg"];
        _noDataImgView.center = CGPointMake(self.view.frame.size.width/2.0,self.view.frame.size.height/2.0-50*SCALEUNIT);
        _noDataImgView.hidden = YES;
    }
    return _noDataImgView;
}
- (UITableView *)ownTableView{
    
    if (_ownTableView == nil) {
        _ownTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 185*SCALEUNIT, self.view.frame.size.width, self.view.frame.size.height-SYSTEM_TOP-(self.frameJudge?220:100)*SCALEUNIT-185*SCALEUNIT) style:UITableViewStylePlain];
        _ownTableView.tableFooterView = [[UIView alloc]init];
        _ownTableView.backgroundColor = [UIColor clearColor];
        _ownTableView.delegate = self;
        _ownTableView.dataSource = self;
    
        _ownTableView.mj_header = [CustomGifHeader headerWithRefreshingBlock:^{
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self loadNewData];
            });
        }];
        _ownTableView.mj_footer = [MJRefreshAutoStateFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    }
    return _ownTableView;
}

#pragma mark ==========UITableView代理方法==========
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return self.num==2?516*SCALEUNIT:396*SCALEUNIT;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    TeachManagementCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TeachManagementCell"];
    if (cell == nil) {
        cell = [[TeachManagementCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TeachManagementCell" WithNum:self.num WithArray:self.subjectTwoSourceArr];
    }
    TeachManagementModel *model = [self.dataArray objectAtIndex:indexPath.row];
    model.isLoading = self.loadState;
    cell.model = model;
    cell.delegate = self;
    cell.buttonsInCellScrollView.buttonsDelegate = self;
    return cell;
}

#pragma mark ==========ButtonsInCellScrollViewDelegate==========
- (void)teachManagementButtonsInCellScrollViewDelegateWithTag:(UIButton *)btn WithID:(long)ID WithitemId:(NSString *)itemId WithProjectName:(NSString *)itemName WithStudentName:(NSString *)studentName{
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic setValue:[NSNumber numberWithLong:ID] forKey:@"id"];
    [dic setValue:itemId forKey:@"itemId"];
    btn.userInteractionEnabled = YES;
    if ([btn.backgroundColor isEqual:[UIColor colorWithHexString:@"#e0e0e0"]]) {
        //执行选中操作
        [self AlertControllerWithMessage:[NSString stringWithFormat:@"是否确认【%@】已掌握【%@】",studentName,itemName] WithDic:dic WithBtn:btn WithItemId:itemId];
    } else if ([btn.backgroundColor isEqual:[UIColor colorWithHexString:@"#676fe9"]]){
        //执行取消操作 
        [self AlertControllerWithMessage:[NSString stringWithFormat:@"是否取消【%@】已掌握【%@】",studentName,itemName] WithDic:dic WithBtn:btn WithItemId:itemId];
    } else{}
}

#pragma mark ==========TFDropDownMenuViewDelegate==========
- (void)menuView:(TFDropDownMenuView *)menu tfColumn:(NSInteger)column WithSelectJudge:(BOOL)selectJudge{
    if (column==0) {
        if (selectJudge) {//正序
            self.countOrder = @"asc";
        }else if (!selectJudge){
            self.countOrder = @"desc";
        }
        if (column==0&&selectJudge) {//正序
            self.countOrder = @"asc";
        }else if (column==0&&!selectJudge){
            self.countOrder = @"desc";
        }else{}
        [self loadDataWithPage:self.size WithCurrStatus:self.currStatus WithCountOrder:self.countOrder WithTrainItem:self.trainItem WithStudentName:self.studentName];
    }else{}
}
- (void)menuView:(TFDropDownMenuView *)menu selectIndex:(TFIndexPatch *)index{
    if (index.column==0) {
    }else {
        if (index.column==1) {
            if (index.section==0) {
                self.trainItem = @"";
            }else{
                for (int i=0; i<self.subjectTwoSourceArr.count; i++) {
                    if ([[self.subjectTwoArr objectAtIndex:index.section] isEqualToString:[[self.subjectTwoSourceArr objectAtIndex:i] objectForKey:@"itemName"]]) {
                        self.trainItem = [NSString stringWithFormat:@"%@",[[self.subjectTwoSourceArr objectAtIndex:i] objectForKey:@"id"]];
                    }
                }
            }
        }else if (index.column==2){
            self.currStatus = index.section;
        }
        [self loadDataWithPage:self.size WithCurrStatus:self.currStatus WithCountOrder:self.countOrder WithTrainItem:self.trainItem WithStudentName:self.studentName];
    }
}

#pragma mark ==========TeachManagementCell代理==========
- (void)teachManagementCellDelegatePhoneWithNum:(NSString *)phone{
    [self phoneOpenWithNum:phone];
}
- (void)phoneOpenWithNum:(NSString *)phone{
    if ([self isSIMInstalled]) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",phone]]];
    }else {
        [self showMessage:@"没有sim卡"];
    }
}
- (BOOL)isSIMInstalled{
    CTTelephonyNetworkInfo *networkInfo = [[CTTelephonyNetworkInfo alloc] init];
    CTCarrier *carrier = [networkInfo subscriberCellularProvider];
    if (!carrier.isoCountryCode) {
        return NO;
    }
    return YES;
}

#pragma mark ==========TeachManagementSearchViewDelegate==========
- (void)teachManagementSearchViewDelegateTextFieldEditWithContent:(NSString *)content{
    self.studentName = content;
    [self loadDataWithPage:self.size WithCurrStatus:self.currStatus WithCountOrder:self.countOrder WithTrainItem:self.trainItem WithStudentName:self.studentName];
}
- (void)teachManagementSearchViewDelegateSearch:(UIButton *)btn WithContent:(NSString *)content{
    btn.userInteractionEnabled = YES;
    self.studentName = content;
    [self loadDataWithPage:self.size WithCurrStatus:self.currStatus WithCountOrder:self.countOrder WithTrainItem:self.trainItem WithStudentName:self.studentName];
}

#pragma mark ==========弹框提示==========
- (void)AlertControllerWithMessage:(NSString *)message WithDic:(NSMutableDictionary *)dic WithBtn:(UIButton *)btn WithItemId:(NSString *)itemId{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[NetworkEngine sharedClient] GETByToken:TEACHMANAGEMENTSUBJECTTWOCHANGE data:dic success:^(id responseObject) {
            if ([[responseObject objectForKey:@"code"] integerValue] == 1) {
                self.loadState = YES;
                NSString *trainItem = [[responseObject objectForKey:@"data"] objectForKey:@"trainItem"];
                if ([trainItem isEqualToString:@""]) {
                    [btn setBackgroundColor:[UIColor colorWithHexString:@"#e0e0e0"]];
                } else if (![trainItem containsString:@","]) {
                    if ([itemId isEqualToString:trainItem]) {
                        [btn setBackgroundColor:[UIColor colorWithHexString:@"#676fe9"]];
                    }else {
                        [btn setBackgroundColor:[UIColor colorWithHexString:@"#e0e0e0"]];
                    }
                } else {
                    NSArray *array = [trainItem componentsSeparatedByString:@","];
                    if ([array containsObject:itemId]) {
                        [btn setBackgroundColor:[UIColor colorWithHexString:@"#676fe9"]];
                    }else {
                        [btn setBackgroundColor:[UIColor colorWithHexString:@"#e0e0e0"]];
                    }
                }
            } else if ([[responseObject objectForKey:@"code"] integerValue] == 2) {
                [self toLoginVC];
            } else {}
        } failure:^(NSString *error) {
            [self showError:error];
        }];
    }]];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alertVC animated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
